package com.study.post.filter.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author : wilbur.yuan
 * @date : 2019-02-18
 */
@Slf4j
public class PermissonFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(
                (HttpServletRequest) servletRequest);
        BufferedReader reader = null;
        String body;
        try {
            reader = new BufferedReader(new InputStreamReader(requestWrapper.getInputStream()));
            body = IOUtils.toString(reader).replaceAll("\t|\n|\r", "");
        } catch (IOException e) {
            log.error("流读取错误："+e);
            return;
        }finally {
            if (null != reader){
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error("流关闭错误："+e);
                }
            }
        }
        Map<String,Object> paramMap = JSON.parseObject(body);
        log.info("post params : {}", paramMap);
        filterChain.doFilter(requestWrapper, servletResponse);
    }
}
